﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace TA.JSON
{
	/// <summary>
	/// JSON extensions for the String class.
	/// </summary>
	public static class _StringExtensions
	{
		/// <summary>
		/// Returns a JSON-escaped version of the specified string.
		/// </summary>
		/// <param name="sThis"></param>
		public static string JsonEscape(this string sThis)
		{
			StringBuilder sb = new StringBuilder();
			sb.Append("\"");
			for (int i = 0; i < sThis.Length; ++i)
			{
				switch (sThis[i])
				{
					case '\r':
						sb.Append("\\r");
						break;
					case '\n':
						sb.Append("\\n");
						break;
					case '\t':
						sb.Append("\\t");
						break;
					case '\f':
						sb.Append("\\f");
						break;
					case '\b':
						sb.Append("\\b");
						break;
					case '\\':
						sb.Append("\\\\");
						break;
					case '\"':
						sb.Append("\\\"");
						break;
					default:
						if (sThis[i] == '\\' && i < sThis.Length - 1)
						{
							if ("btnfr\"\\".IndexOf(sThis[i + 1]) != -1)
							{
								sb.Append("\\\\"); // "\\"
								if (sThis[i + 1] == '\\')
									sb.Append("\\\\"); // "\\"
								else
									sb.Append(sThis[i + 1]);
								++i;
								continue;
							}
						}
						sb.Append(sThis[i]);
						break;
				}
			}
			sb.Append("\"");
			return sb.ToString();
		}
	}
}
